package com.googlecode.garbagecan.commons.clistudy.mycli;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CommandParser {
	private Options options;
	private Option optHelp;
	private Option optVersion;
	private Option optStart;
	private Option optStop;
	public CommandParser() {
		optHelp = new Option("h", false, "print this help and exit");
		optVersion = new Option("v", false, "print version information and exit");
		optStart = new Option("start", false, "start server");
		optStop = new Option("stop", false, "stop server");
		
		options = new Options();
		options.addOption(optHelp);
		options.addOption(optVersion);
		options.addOption(optStart);
		options.addOption(optStop);
	}

	public Command parse(String[] args) {
		CommandLineParser parser = new BasicParser();
		CommandLine cl = null;
		Command cmd;

		try {
			cl = parser.parse(options, args);
		} catch (ParseException ex) {
			return new HelpCommand();
		}

		Option[] opts = cl.getOptions();

		if (opts == null) {
			cmd = new HelpCommand();
		} else if (cl.hasOption(optHelp.getOpt())) {
			cmd = new HelpCommand();
		} else if (cl.hasOption(optVersion.getOpt())) {
			cmd = new VersionCommand();
		} else if (cl.hasOption(optStart.getOpt())) {
			cmd = new StartCommand();
		} else if (cl.hasOption(optStop.getOpt())) {
			cmd = new StopCommand();
		} else {
			if (opts.length == 0 && cl.getArgList().size() == 1 &&cl.getArgList().get(0).equals("run")) {
				cmd = new RunCommand();
			} else {
				cmd = new HelpCommand();
			}
		}
		return cmd;
	}
	
	public Options getOptions() {
		return this.options;
	}
}
